import Event from 'events'

class BaseWorker extends Event {
  constructor(worker) {
    super()

    this.worker = worker

    this.worker.onmessage = event => {
      this.emit(event.data.type, event.data)
    }
  }

  postToSocket(data) {
    this.postMessage('EMIT2SOCKET', data)
  }

  postMessage(action, data) {
    if (!this.worker) {
      throw new Error('[Worker] worker was not finalize!')
    }
    this.worker.postMessage({
      action,
      data
    })
  }

  listenMessage(list) {
    if (typeof list !== 'object') {
      throw new Error('[Worker] list expected a object!')
    }
    for (const key in list) {
      this.on(key, list[key])
    }
  }

  removeListenMessage(list) {
    if (typeof list !== 'object') {
      throw new Error('[Worker] list expected a object!')
    }
    for (const key in list) {
      this.remove(key, list[key])
    }
  }
}

export default BaseWorker
